package com.duolaibei.pay.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatCheckBox;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.duolaibei.pay.R;
import com.duolaibei.pay.base.BaseActivity;
import com.duolaibei.pay.base.Constants;
import com.duolaibei.pay.bean.PayOrder;
import com.duolaibei.pay.greendao.PayOrderDao;
import com.duolaibei.pay.smscan.SunmiAppIdScanActivity;
import com.duolaibei.pay.utils.DateUtils;
import com.duolaibei.pay.utils.GreenDaoManager;
import com.duolaibei.pay.utils.SharedPreferencesUtils;
import com.duolaibei.pay.utils.TimeUtils;
import com.duolaibei.pay.utils.ToastUtils;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import pub.devrel.easypermissions.EasyPermissions;

//import com.landicorp.android.scan.scanDecoder.ScanDecoder;
//import com.landicorp.android.scan.scanDecoder.ScanDecoderParameter;

/**
 * APPID保存设置
 */
public class MainActivity extends BaseActivity {

    @Bind(R.id.appid)
    EditText appid;
    @Bind(R.id.secret_key)
    EditText secretKey;
    @Bind(R.id.terminal_number)
    EditText terminalNumber;
    @Bind(R.id.speech_check)
    AppCompatCheckBox speechCheck;
    @Bind(R.id.save_setting)
    TextView saveSetting;
    @Bind(R.id.workmen_id)
    EditText workmenId;
    @Bind(R.id.front_check)
    AppCompatCheckBox frontCheck;
    @Bind(R.id.front_check_layout)
    LinearLayout frontCheckLayout;
    @Bind(R.id.back)
    RelativeLayout back;

    private final int REQUEST_CODE = 100;
    private final int CAMERA_CODE = 0;
    private String result;
    private PayOrderDao payOrderDao = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        payOrderDao = GreenDaoManager.getInstance().getNewSession().getPayOrderDao();
        List<PayOrder> orders = payOrderDao.queryBuilder().list();
        for (PayOrder order : orders) {
            int days = DateUtils.getBetweenDay(TimeUtils.strToDate(order.getPaytime() + "000", "yyyy-MM-dd HH:mm:ss"), new Date());
            // 大于手机当前时间15天的记录删除
            if (days > 15)
                payOrderDao.deleteByKey(order.getId());
        }
        if (isShowView()) {
            Intent intent = new Intent(this, HomepageActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            goToHomeActivity();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void goToHomeActivity() {
        Intent intent = new Intent(this, HomepageActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    protected boolean isShowView() {
        String appid = SharedPreferencesUtils.getAppid();
        if (null != appid) {
            if (appid.length() > 0) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    @Override
    public int getContentViewResId() {
        return R.layout.activity_main;
    }

    int isfrontCamera = 1; //没有前置摄像头

    @Override
    public void intiViews() {
        back.setOnClickListener(this);
        saveSetting.setOnClickListener(this);
        appid.setText(SharedPreferencesUtils.getAppid());
        secretKey.setText(SharedPreferencesUtils.getAppSecret());
        terminalNumber.setText(SharedPreferencesUtils.getTerminalNumber());
        speechCheck.setChecked(SharedPreferencesUtils.getPlaySpeak().equals("1") ? true : false);
        workmenId.setText(SharedPreferencesUtils.getWorkMenId());
        Log.i("TAG",SharedPreferencesUtils.getAppid());
        Log.i("TAG",SharedPreferencesUtils.getAppSecret());
        Log.i("TAG",SharedPreferencesUtils.getTerminalNumber());
        Log.i("TAG",SharedPreferencesUtils.getWorkMenId());
        serach.setVisibility(View.VISIBLE);
        serach.setText("扫一扫");
        serach.setOnClickListener(this);
        if (isfrontCamera != 0) {
            frontCheckLayout.setVisibility(View.GONE);
        } else if (isfrontCamera == 0) {
            frontCheckLayout.setVisibility(View.VISIBLE);
            frontCheck.setChecked(SharedPreferencesUtils.getFrontChecked().equals("1") ? true : false);
        }
    }


    @Override
    public String setTitle() {
        return getString(R.string.setting_text);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.save_setting) {
            if (saveData()) {
                Intent intent = new Intent(this, HomepageActivity.class);
                startActivity(intent);
            }
        } else if (view.getId() == R.id.serach) {
            String[] perms = {Manifest.permission.CAMERA};
            if (EasyPermissions.hasPermissions(this, perms)) {//检查是否获取该权限
                Intent qrIntent = new Intent(this, SunmiAppIdScanActivity.class);
                startActivityForResult(qrIntent, REQUEST_CODE);
            } else {
                EasyPermissions.requestPermissions(this, getString(R.string.get_permissions_tips), CAMERA_CODE, perms);
            }
        } else if (view.getId() == R.id.back) {
            goToHomeActivity();
        }
    }

    /**
     * 保存用户的配置数据
     */
    protected boolean saveData() {
        Map<String, String> map = new HashMap<>();
        String appidText = appid.getText().toString().trim();
        String appSecret = secretKey.getText().toString().trim();
        String number = terminalNumber.getText().toString().trim();
        String wokmenId = workmenId.getText().toString().trim();
        //选择语音提示1，否则为0；
        String playSpeak = speechCheck.isChecked() ? "1" : "0";
        if (appidText.equals("")) {
            ToastUtils.showToast(this, R.string.appid_input_tips);
            return false;
        }
        if (appSecret.equals("")) {
            ToastUtils.showToast(this, R.string.appid_input_tips);
            return false;
        }
        if (number.equals("")) {
            ToastUtils.showToast(this, R.string.terminal_number);
            return false;
        }
        map.put(Constants.APP_ID, appidText);
        map.put(Constants.APP_SECRET, appSecret);
        map.put(Constants.CODE, number);
        map.put(Constants.SPEAK_PLAY, playSpeak);
        map.put(Constants.WORK_MEN_ID, wokmenId);
        if (isfrontCamera == 0) {
            //前置摄像头选择1为选中，-1未选中
            String isChecked = frontCheck.isChecked() ? "1" : "-1";
            map.put(Constants.IS_FRONT_CAMERA, isChecked);
        }
        SharedPreferencesUtils.addMultipleToSharedPreferences(this, Constants.APP_INFO_SP_NAME, map);
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(Constants.SCAN_STATE) != 0) {
                    result = bundle.getString(Constants.SCAN_CONTENT);
                    String[] strs = result.split(";");
                    if (strs == null || strs.length < 4) {
                        return;
                    }
                    appid.setText(strs[0]);
                    secretKey.setText(strs[1]);
                    terminalNumber.setText(strs[2]);
                    workmenId.setText(strs[3]);
                    workmenId.requestFocus();
                    workmenId.setSelection(workmenId.getText().length());
                } else if (bundle.getInt(Constants.SCAN_STATE) == 0) {
                    Toast.makeText(this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}